<?php

namespace App\Http\Controllers\Admin;

use App\Http\Requests\AdminWxMaterialNewsPost;
use Illuminate\Http\Request;
use App\Services\WxMaterialService;

/**
 * 微信图文素材管理
 * @package App\Http\Controllers\Admin
 */
class WxMaterialNewsController extends BaseController
{
    private $materialSer;

    /**
     * 构造函数
     */
    public function __construct()
    {
        $this->materialSer = new WxMaterialService();
    }

    /**
     * 素材首页列表
     * @param Request $request
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     */
    public function index(Request $request)
    {
        \App\Jobs\WxMaterialNewsUpload::dispatch(1)->onQueue('low');
        if ($request->ajax()) {
            $pageSize = $request->get('pageSize', 10);
            $query = \App\Models\WxMaterial::select('*');
            $keyword = $request->get('keyword', '');
            if ($keyword) {
                $query->where('name', 'like', '%' . $keyword . '%');
            }
            return $query->paginate($pageSize);
        }
        return view('admin.wxmaterialnews.index', $this->viewData);
    }

    /**
     * 创建素材
     * @param AdminWxMaterialNewsPost $request
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\Http\Response|\Illuminate\View\View
     */
    public function form(Request $request)
    {
        //素材分组数据
        $catList = $this->materialSer->getCatList(WxMaterialService::TYPE_NEWS);
        $this->viewData['catList'] = $catList;
        return view('admin.wxmaterialnews.form', $this->viewData);
    }

    /**
     * 保存素材数据
     * @param AdminWxMaterialNewsPost $request
     * @return \Illuminate\Http\Response
     */
    public function save(AdminWxMaterialNewsPost $request)
    {
        if ($request->ajax()) {
            try {
                $this->materialSer->createMaterial(WxMaterialService::TYPE_NEWS)->save($request->toArray());
                return $this->showMsg('success', '保存成功', [], 'admin.sysmenugroup.index');
            } catch (\Exception $e) {
                return $this->showMsg('error', '保存失败:' . $e->getMessage());
            }
        }
    }
}
